package com.agile.leetcode.tomcat.nio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Objects;

/**
 * 封装nio请求
 *
 * @Author KD
 * @Date 2021/2/7 11:31
 */
public class MyNioRequest {
    /**
     * 请求路径
     */
    private String url;
    /**
     * 请求方法
     */
    private String method;

    public MyNioRequest(SelectionKey selectionKey) {
        // 拿到通道
        SocketChannel channel = (SocketChannel) selectionKey.channel();
        // 封装请求
        ByteBuffer buffer = ByteBuffer.allocate(10 * 1024);
        // 定义http请求体数据
        String body = "";
        // 读取数据
        try {
            int read = channel.read(buffer);
            if (read != -1) {
                // 拿到字符串数据
                body = new String(buffer.array());
                if (!Objects.equals("", body)) {
                    // http协议是以头分割的
                    String[] split = body.split("\n");
                    // 拿到url地址
                    // 拿到头部
                    String httpHead = split[0];
                    url = httpHead.split("\\s")[1];
                    // 拿到方法
                    method = httpHead.split("\\s")[0];
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getUrl() {
        return url;
    }

    public String getMethod() {
        return method;
    }
}
